# 定义一个类：WordGuessGame
class WordGuesserGame

  # add the necessary class methods, attributes, etc. here
  # to make the tests in spec/wordguesser_game_spec.rb pass.
  # 添加必须的类的方法，属性等等，尝试通过spec/wordguesser_game_spec.rb中的测试

  # Get a word from remote "random word" service
  # 从远程的“random word”服务中获取一个单词 
  # 构造器，传入一个参数word，然后赋值给实例变量@word，初始化@guesses、wrong_guesses
  def initialize(word)
    # 记录单词本身
    @word = word
    puts "@word init:"+@word

    # 这个是猜对的单词列表
    @guesses = ""
    # 这个是猜错的单词列表
    @wrong_guesses = ""

    @guesscount = 0
  end


  # You can test it by installing irb via $ gem install irb
  # and then running $ irb -I. -r app.rb
  # And then in the irb: irb(main):001:0> WordGuesserGame.get_random_word
  #  => "cooking"   <-- some random word
  # 你能通过借助$ gem install irb安装irb来测试它
  # 并且接着运行$ irb -I. -r app.rb
  # 接着在irb中
  def self.get_random_word
    require 'uri'
    require 'net/http'
    # 下面这个链接能够获取随机单词
    uri = URI('http://randomword.saasbook.info/RandomWord')
    Net::HTTP.new('randomword.saasbook.info').start { |http|
      return http.post(uri, "").body
    }
  end

  # 定义三个属性的get和set方法：word、guesses、wrong_guesses，使用attr_accessor之间实现get和set
  # def word()
  #   return @word
  # end

  # def guesses()
  #   return @guesses
  # end

  # def wrong_guesses()
  #   return @wrong_guesses
  # end

  # 注意下述定义形式，实例变量前不需要@，冒号与变量直接连接
  attr_accessor :word
  attr_accessor :guesses
  attr_accessor :wrong_guesses
  


  # 添加guess方法，判断单词word中是否包含字母
  def guess(letter)

    unless letter =~ /[a-zA-Z]/
      raise ArgumentError
    end

    # 首先进行参数合法性判断
    if letter==''
      raise ArgumentError
    elsif letter == nil
      raise ArgumentError
    end


    # 然后将参数转换成小写，然后进行逻辑判断
    letter.downcase!


    puts "@word guess:"+@word
    if @word[letter]
      puts "@guesses init:"+@guesses
      if @guesses[letter]
        return false
      else
        @guesses = @guesses+letter        
        return true
      end
    else
        # 统计猜错的次数
        @guesscount = @guesscount +1
      if @wrong_guesses[letter]
        return false
      else
        @wrong_guesses = @wrong_guesses + letter
        return true
      end
    end
  end

  # 使用guesses展示word
  def word_with_guesses
    # 进行猜测字符串替换
    # 必须要使用clone的方式，使用“=”会将地址赋给guessword，修改guessword会造成对@word值的修改
    guessword = @word.clone
    guessword.chars do |letter|
      if !@guesses[letter]
        guessword.tr!(letter,"-")
      end
    end

    return guessword
  end

  # 进行输赢检查
  def check_win_or_lose
    guessword = word_with_guesses
   
    puts "guessword:"+guessword
    puts "@word:"+@word

    if @guesscount>=7
      return :lose
    elsif guessword==@word
      return :win
    else 
      return :play
    end
  end


end
